package com.cavy.platform.server.domain;

import com.cavy.platform.server.BeansProvider;
import com.cavy.platform.server.domain.job.Job;
import com.cavy.platform.server.domain.job.JobId;
import com.cavy.platform.server.domain.message.HeartbeatMessage;
import com.cavy.platform.server.dto.AgentStatusDto;
import com.cavy.platform.server.repository.AgentRepository;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 宿主机
 */
@Data
@Accessors(chain = true)
public class Agent {
    private String hostname;
    private String address;
    private String systemName;

    private String agentVersion;
    private long maxMemory;
    private int maxJobCount;

    private AgentStatus status = AgentStatus.ENABLE;
    private Date lastHeartbeat = new Date();
    //任务列表
    private List<JobId> jobList = new ArrayList<>();

    //心跳
    public void heartbeat(HeartbeatMessage message) {
        lastHeartbeat = new Date();
    }

    //禁用|启用
    public void statusChange(AgentStatusDto dto) {
        if (status.equals(dto.getStatus())) {
            return;
        }
        this.status = dto.getStatus();
    }

    public boolean available() {
        return AgentStatus.ENABLE.equals(status);
    }

    public void addJob(Job job) {
        jobList.add(new JobId(job));
        save();
    }

    private void save() {
        Objects.requireNonNull(BeansProvider.getBean(AgentRepository.class)).save(this);
    }

    public void stop(JobId job) {
        jobList.remove(job);
        save();
    }

    public void updateLastHeartbeatTime(Date lastHeartbeatTime) {
        this.lastHeartbeat = lastHeartbeatTime;
        save();
    }
}
